{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9b708c18-a910-4382-af52-c1632b5ee408",
   "metadata": {},
   "source": [
    "# Python编程基础及示例\n",
    "Python编程中的关键概念\n",
    "- 变量与数据类型\n",
    "- 控制流\n",
    "- 函数\n",
    "- 面向对象编程\n",
    "- 错误与异常处理\n",
    "- 文件I/O"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea6e53c3-948d-4af9-a62c-a2a09a220575",
   "metadata": {},
   "source": [
    "## 变量与数据类型\n",
    "- 数值型\n",
    "  - 整数\n",
    "  - 浮点数\n",
    "  - 复数\n",
    "- 序列类型\n",
    "  - 字符\n",
    "  - 列表\n",
    "  - 元组\n",
    "- 字典\n",
    "- 集合\n",
    "- 布尔型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40310d6f-9d59-42de-858f-d20536a55007",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 复数\n",
    "c = 5 + 6j\n",
    "print(c.real)    # 实部（Real），结果为5.0\n",
    "print(c.imag)    # 虚部（Imaginary），结果为6.0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e528e594-c24e-4a35-9b24-940e19775855",
   "metadata": {},
   "source": [
    "### 字符串示例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "755b0ec4-5af5-4404-837e-1b8dfd6e933f",
   "metadata": {},
   "outputs": [],
   "source": [
    "text = \"Hello, MageEdu!\"\n",
    "print(text[7:])      # 输出“MageEdu!”（索引7到字符串末尾）\n",
    "print(text[:5])      # 输出“Hello”（索引0到4）\n",
    "print(text[7:11])    # 输出“Mage”（索引7到10）\n",
    "print(text[-8:-4])   # 输出“Mage” （索引-8到-5）\n",
    "print(text[:])       # 输出整个字符串\n",
    "print(text[::2])     # 输出整个字符串中索引编号为0或偶数的字符\n",
    "print(text[::-1])    # 逆序返回整个字符串的所有字符\n",
    "\n",
    "filename = \"document.txt\" \n",
    "print(filename[-4:])        # 输出: '.txt'\n",
    "\n",
    "name = \"Tom\"; age = 5\n",
    "print(f\"{name} is {age} years old.\")  # 输出: \"Tom is 5 years old.\"\n",
    "\n",
    "text = \"I like Java\"\n",
    "print(text.replace(\"Java\", \"Python\"))  # 输出: \"I like Python\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0802ec1c-1391-4020-bb6f-28232bb4f8a0",
   "metadata": {},
   "source": [
    "### 列表示例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d682533-1ccb-4bb7-9bcd-3879915ac2fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 生成平方数并过滤出偶数\n",
    "squares = [x**2 for x in range(10) if x%2==0]  # [0,4,16,36,64]\n",
    "print(squares)\n",
    "\n",
    "# 二维矩阵展开\n",
    "matrix = [[1,2],[3,4]]\n",
    "flat = [num for row in matrix for num in row]  # [1,2,3,4]\n",
    "print(flat)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04326105-8f9d-4c74-9232-3487a0893cf1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 列表方法示例\n",
    "ages = [37, 23, 29, 31]\n",
    "print(ages)\n",
    "\n",
    "ages.sort()  # 原地排序，即原列表变为 [23, 29, 31, 37]\n",
    "print(ages)\n",
    "\n",
    "ages.sort(reverse=True)  # 原地逆序排序，即原列表变为 [37, 31, 29, 23]\n",
    "print(ages)\n",
    "\n",
    "ages.reverse()  # 原地逆序排序，与“sort(reverse=True)”的作用相同\n",
    "print(ages)\n",
    "\n",
    "ages = sorted(ages)   # sorted()函数会对指定列表元素进行排序，并将排序结果以新列表进行返回\n",
    "print(ages)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "119e657d-8b8c-4993-a2ed-891c94c534da",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 深复制与浅复制示例\n",
    "import copy\n",
    "\n",
    "# 原始列表（包含嵌套列表）\n",
    "original = [1, [2, 3], {\"a\": 4}]\n",
    "\n",
    "# 浅复制实验\n",
    "shallow = original[:]\n",
    "shallow[1][0] = 100\n",
    "print(original)  # 输出[1, [100, 3], {'a': 4}] → 子列表被同步修改\n",
    "\n",
    "# 深复制实验\n",
    "deep = copy.deepcopy(original)\n",
    "deep[1][0] = 200\n",
    "print(original)  # 输出仍为[1, [100, 3], {'a': 4}] → 完全独立"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13466cb7-d798-4fdc-930f-674e0e5f2fad",
   "metadata": {},
   "source": [
    "### 元组示例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3cc541f6-d0f9-4b50-aafe-343f55097536",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 元组定义方法\n",
    "t1 = (1, \"Hi\", 3.14)    # 标准定义\n",
    "t2 = 1, 2, 3            # 省略括号（推荐仅用于明确场景）\n",
    "print(t1, t2)\n",
    "\n",
    "empty_tuple1 = ()       # 空元组，最简洁的创建方式\n",
    "empty_tuple2 = tuple()  # 等效于空括号写法\n",
    "print(empty_tuple1, empty_tuple2)\n",
    "\n",
    "# 单个元素的元组的定义\n",
    "t3 = (50)   # 整型50（错误写法，实际类型为int）\n",
    "t4 = (50,)  # 单元素元组（正确写法）\n",
    "print(t3, t4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e6c6349-a213-4ff2-84c0-d606661c8c06",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 元组解包\n",
    "a, b, c = (10, 20, 30)          # 解包赋值，将元组元素分配给多个变量\n",
    "print(a, b, c)\n",
    "\n",
    "first, *rest = (1, 2, 3, 4)     # 星号解包，用于处理不定长元素，rest → [2,3,4]\n",
    "print(first, rest)\n",
    "\n",
    "def get_coords():\n",
    "     return 10, 20  # 函数返回值打包，隐式返回元组（自动打包为元组）\n",
    "print(get_coords())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b92c7730-bf79-4012-99db-0095b822b526",
   "metadata": {},
   "source": [
    "### 集合示例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "517a4d75-cad7-4b6a-8ae0-83dd01ca7d83",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 集合定义方法\n",
    "fruits = {\"apple\", \"banana\", \"cherry\"}        # 非空集合 \n",
    "empty_set = set()                             # 空集合（必须使用set()，{}表示空字典）\n",
    "\n",
    "numbers = set([1, 2, 2, 3, 4])                # 类型转换，输出为列表，输出为字典{1, 2, 3, 4}\n",
    "\n",
    "evens = {x for x in range(10) if x % 2 == 0}  # 类似列表推导式，生成集合，{0, 2, 4, 6, 8}\n",
    "print(fruits, empty_set, numbers, evens)\n",
    "\n",
    "if \"apple\" in fruits:                         # 成员存在性判断\n",
    "    print(\"存在\")\n",
    "    \n",
    "fs = frozenset([1, 2, 3])                     # 不可变集合\n",
    "# fs.add(4)                                   # 会抛出异常"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01df5c46-5937-4bed-afdd-adb761c6e0d7",
   "metadata": {},
   "source": [
    "### 字典示例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3c00a7b-1ae0-4f2f-b8b3-2f376a6cce01",
   "metadata": {},
   "outputs": [],
   "source": [
    "user = {\"name\": \"张三\", \"age\": 25}             # 标准定义\n",
    "user2 = dict([(\"name\", \"李四\"), (\"age\", 30)])  # 键值对列表转换\n",
    "\n",
    "squares = {x: x**2 for x in range(5)}  # {0:0, 1:1, 2:4, 3:9, 4:16}\n",
    "\n",
    "print(user, user2, squares)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bac9ad8e-fbc2-4045-a7e6-cb5aeb0b7d29",
   "metadata": {},
   "source": [
    "## 控制流\n",
    "- 条件语句\n",
    "- 循环语句"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "675bffe9-04aa-4111-bdbf-832b84c79d17",
   "metadata": {},
   "source": [
    "### 条件语句"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c2e54fd-c12d-4e95-8306-9e0295ef6d9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 条件语句示例\n",
    "# 单分支if语句\n",
    "score = 76\n",
    "if score >= 60:\n",
    "    print(\"及格\")        # 条件为True时执行\n",
    "\n",
    "# 双分支if语句\n",
    "password = \"http://www.magedu.com\"\n",
    "if password == \"MageEdu.Com\":\n",
    "    print(\"登录成功\")\n",
    "else:\n",
    "    print(\"密码错误\")     # 条件为False时执行\n",
    "\n",
    "# 多分支if语句\n",
    "temperature = 42\n",
    "if temperature < 10:\n",
    "    print(\"寒冷模式\")\n",
    "elif 10 <= temperature < 25:\n",
    "    print(\"舒适模式\")\n",
    "else:\n",
    "    print(\"高温模式\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d625ee39-67d6-4765-8dfe-2f165a693090",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 三元表达式示例\n",
    "is_rainy = True\n",
    "action = \"带伞\" if is_rainy else \"不带伞\"  # 结果：\"带伞\" \n",
    "\n",
    "# 返回值优化\n",
    "def check_even(n):\n",
    "    return \"偶数\" if n % 2 == 0 else \"奇数\"  # 结合异常处理更健壮\n",
    "\n",
    "# 与列表推导式结合\n",
    "nums = [1, 2, 3, 4]\n",
    "new_nums = [x*2 if x%2==0 else x for x in nums]  # 结果：[1,4,3,8] \n",
    "\n",
    "# 与字典推导式结合\n",
    "keys = ['a', 'b', 'c']\n",
    "values = [1, 2, 3]\n",
    "my_dict = {k: ('even' if v%2==0 else 'odd') for k, v in zip(keys, values)}  # 动态值生成 \n",
    "\n",
    "print(action, check_even(17), new_nums, my_dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a82852e2-58e2-4e90-b9c1-c82e97688abc",
   "metadata": {},
   "source": [
    "### 循环\n",
    "- for循环\n",
    "- while循环"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d477fb40-6781-4939-b142-f271096dac5c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# for循环示例\n",
    "# 针对字符串，for循环会逐个字符进行迭代\n",
    "for char in \"Hello\":\n",
    "    print(char)  # 输出：H → e → l → l → o\n",
    "    \n",
    "# 针对字典，for循环默认进行键遍历，也可结合特定的方法获取值或键值对\n",
    "person = {\"name\": \"Alice\", \"age\": 30}\n",
    "for key in person:                 # 遍历键\n",
    "    print(key)                     # 输出：name → age\n",
    "for key, value in person.items():  # 遍历键值对\n",
    "    print(f\"{key}: {value}\")       # 输出：name: Alice → age: 30\n",
    "    \n",
    "# 也可使用range()生成整数序列，从而进行固定次数的循环\n",
    "# 生成0-4的数列（不包含5）\n",
    "for i in range(5):\n",
    "    print(i)  # 输出：0 → 1 → 2 → 3 → 4\n",
    "\n",
    "# 指定步长和范围（2到10，步长为3）\n",
    "for i in range(2, 11, 3):\n",
    "    print(i)  # 输出：2 → 5 → 8\n",
    "    \n",
    "# enumerate()可同时获取可迭代对象的元素索引与值\n",
    "for index, fruit in enumerate(fruits):\n",
    "    print(f\"Index {index}: {fruit}\")  # 输出：Index 0: apple → ...\n",
    "    \n",
    "# zip()支持并行遍历多个序列\n",
    "names = [\"Alice\", \"Bob\"]\n",
    "ages = [25, 30]\n",
    "for name, age in zip(names, ages):\n",
    "    print(f\"{name} is {age}\")  # 输出：Alice is 25 → Bob is 30[7](@ref)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "239c0d1d-d957-47be-9eb6-d5146a54ec54",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 列表生成式\n",
    "# 传统写法\n",
    "squares = []\n",
    "for x in range(5):\n",
    "    squares.append(x**2)\n",
    "\n",
    "# 列表生成式写法\n",
    "squares = [x**2 for x in range(5)]  # 输出：[0, 1, 4, 9, 16]\n",
    "\n",
    "# 通过if子句过滤元素，支持单条件或多条件并列\n",
    "# 仅保留偶数\n",
    "even_numbers = [x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]\n",
    "# 同时满足两个条件（等价于逻辑与）\n",
    "multi_condition = [x for x in range(20) if x % 2 == 0 if x % 3 == 0]  # [0, 6, 12, 18]\n",
    "\n",
    "print(squares, even_numbers, multi_condition)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3cd31123-025b-464a-8661-508836e00653",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 列表生成式与三元表达式相结合\n",
    "# 负数归零处理\n",
    "data = [-5, 3, -2, 8]\n",
    "clean_data = [x if x >= 0 else 0 for x in data]  # [0, 3, 0, 8]\n",
    "print(clean_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10cdb42b-e8cc-49ed-9931-c549d34d17b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 列表生成式嵌套\n",
    "# 二维矩阵展平\n",
    "matrix = [[1, 2], [3, 4], [5, 6]]\n",
    "flat = [num for row in matrix for num in row]  # [1, 2, 3, 4, 5, 6]\n",
    "\n",
    "# 生成笛卡尔积坐标\n",
    "coordinates = [(x, y) for x in range(3) for y in range(3)]  # [(0,0), (0,1), ..., (2,2)]\n",
    "print(flat, coordinates)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b0632b5f-770e-4c75-9b15-35fdacc2ff1a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 生成式与字典、集合\n",
    "# 字典生成示例： 生成数字平方映射\n",
    "square_dict = {x: x**2 for x in range(5)}  # {0:0, 1:1, 2:4, 3:9, 4:16}\n",
    "\n",
    "# 集合生成示例：字符串去重\n",
    "text = \"abracadabra\" \n",
    "unique_chars = {char for char in text}  # {'a', 'b', 'c', 'd', 'r'}\n",
    "\n",
    "print(square_dict, unique_chars)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b8ff6fb-d377-4347-8187-d42c5b814bf0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 生成器表达式：惰性\n",
    "# 处理百万级数据（内存友好）\n",
    "big_data = (x**2 for x in range(10**6))  # 使用时逐个生成，不占用全部内存\n",
    "\n",
    "print(big_data)\n",
    "\n",
    "i = 0\n",
    "while i <= 10:\n",
    "    print(next(big_data))   # 惰性验证\n",
    "    i += 1\n",
    "\n",
    "# 生成器仅可遍历一次\n",
    "gen = (x for x in range(3))\n",
    "print(list(gen))  # [0, 1, 2]\n",
    "print(list(gen))  # []（已耗尽）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9bafa1f-09f6-41d0-9989-864f92a82327",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 利用嵌套生成多维数据结构\n",
    "matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n",
    "transpose = [[row[i] for row in matrix] for i in range(3)]  # [[1,4,7], [2,5,8], [3,6,9]]\n",
    "print(transpose)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8fba8064-845b-4c01-a277-0a1d4b497ad8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# while循环和break\n",
    "password = \"\"\n",
    "while password != \"MageEdu.com\":  # 条件：密码匹配\n",
    "    password = input(\"请输入密码：\")\n",
    "    if password == \"exit\":       # 支持中途退出\n",
    "        print(\"已取消验证\")\n",
    "        break\n",
    "else:  # 仅当未触发break时执行\n",
    "    print(\"验证通过！\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eee49f02-15f8-4b4d-a073-ca0853086561",
   "metadata": {},
   "source": [
    "## 函数示例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c8c2a060-e036-4e81-b64f-75e9c9480ae3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 参数类型与参数调用\n",
    "# 位置参数\n",
    "def greet(name, age):  \n",
    "    print(f\"{name}今年{age}岁\")\n",
    "greet(\"Trump\", 78)               # 正确调用\n",
    "\n",
    "# 默认参数\n",
    "def greet(name: str, message: str = \"Hello\"):\n",
    "    print(f\"{message}, {name}!\")\n",
    "\n",
    "greet(\"Trump\")  # 输出：Hello, Trump!\n",
    "\n",
    "# 关键字参数\n",
    "def describe_person(name, age, city):\n",
    "    print(f\"{name} is {age} years old, living in {city}\")\n",
    "\n",
    "# 通过关键字参数调用（顺序无关）\n",
    "print(describe_person(age=78, city=\"Washington\", name=\"Trump\"))\n",
    "\n",
    "# 通过**将字典解包为关键字参数\n",
    "# import mysql.connector\n",
    "config = {\"host\": \"localhost\", \"port\": 3306, \"user\": \"root\"}\n",
    "# connect(**config)          # 等效于 connect(host=\"localhost\", port=3306, user=\"root\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68e0ae87-6375-4d6f-adb2-23017e741e61",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 可变位置参数\n",
    "def sum_values(a, b, *args):\n",
    "    total = a + b\n",
    "    for num in args:\n",
    "        total += num\n",
    "    return total\n",
    "\n",
    "print(sum_values(1, 2, 3, 4))         # 输出：10（1+2+3+4）\n",
    "\n",
    "# 动态累加\n",
    "def average(*nums):\n",
    "    return sum(nums) / len(nums) if nums else 0\n",
    "print(average(5, 10, 15))  # 输出：10.0\n",
    "\n",
    "# 参数解包\n",
    "values = [2, 4, 6, 8]\n",
    "print(average(*values))  # 解包后等价于average(2,4,6,8) → 输出：5.0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "965f5b84-d1d7-4174-ab4b-c52bb895ff70",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 可变关键字参数\n",
    "def example(a, b=0, *args, c=10, **kwargs):\n",
    "    print(f\"a={a}, b={b}, args={args}, c={c}, kwargs={kwargs}\")\n",
    "\n",
    "example(1, 2, 3, 4, c=5, x=6, y=7)\n",
    "# 输出：a=1, b=2, args=(3,4), c=5, kwargs={'x':6, 'y':7}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18052c69-ed39-4c0d-a74b-9f80badb069f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 参数解包机制\n",
    "def func(a, b, c): \n",
    "    print(a, b, c)\n",
    "args = [1, 2, 3]\n",
    "kwargs = {'a':1, 'b':2, 'c':3}\n",
    "func(*args)      # 等效于func(1,2,3)\n",
    "func(**kwargs)   # 等效于func(a=1, b=2, c=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3273d10b-8710-4741-9b56-0fda227703c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 匿名函数示例\n",
    "# 普通函数\n",
    "def add(x, y):\n",
    "    return x + y\n",
    "\n",
    "# 等效的 lambda 表达式\n",
    "add_lambda = lambda x, y: x + y\n",
    "\n",
    "print(add(2, 3))         # 输出 5\n",
    "print(add_lambda(2, 3))  # 输出 5\n",
    "\n",
    "# 嵌入匿名函数\n",
    "is_positive = lambda x: x > 0\n",
    "print(is_positive(5))  # True\n",
    "\n",
    "# 直接嵌入表达式\n",
    "result = (lambda a, b: a**2 + b**2)(3, 4)\n",
    "print(result)  # 25"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e059219a-a3a2-41c5-937a-098fe073046d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 匿名函数作为高阶函数示例\n",
    "# 同sorted函数一起使用\n",
    "students = [(\"Alice\", 90), (\"Bob\", 85), (\"Charlie\", 92)]\n",
    "# 按成绩升序排序\n",
    "sorted_by_score = sorted(students, key=lambda x: x[1])\n",
    "print(sorted_by_score)  # [('Bob',85), ('Alice',90), ('Charlie',92)]\n",
    "\n",
    "# 同map函数一起使用\n",
    "numbers = [1, 2, 3, 4]\n",
    "squared = list(map(lambda x: x**2, numbers))\n",
    "print(squared)  # [1, 4, 9, 16]\n",
    "\n",
    "# 同filter函数一起使用\n",
    "numbers = [1, 2, 3, 4, 5]\n",
    "even = list(filter(lambda x: x % 2 == 0, numbers))\n",
    "print(even)  # [2, 4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "08362053-dd41-4121-9117-fe57a75697c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 函数装饰器示例\n",
    "def log_calls(func):\n",
    "    \"\"\"\n",
    "    这是一个日志装饰器，用于记录函数被调用的信息。\n",
    "    它接受一个函数 func 作为参数，并返回一个新的函数。\n",
    "    \"\"\"\n",
    "    def wrapper(*args, **kwargs):\n",
    "        \"\"\"\n",
    "        这个内部的 wrapper 函数是实际被调用的新函数。\n",
    "        它封装了原始函数 func。\n",
    "        \"\"\"\n",
    "        print(f\"正在调用函数: {func.__name__}，参数: {args}, {kwargs}\")\n",
    "        result = func(*args, **kwargs) # 调用原始函数\n",
    "        print(f\"函数 {func.__name__} 调用完毕，结果: {result}\")\n",
    "        return result\n",
    "    return wrapper\n",
    "\n",
    "@log_calls\n",
    "def add(a, b):\n",
    "    \"\"\"一个简单的加法函数\"\"\"\n",
    "    return a + b\n",
    "\n",
    "@log_calls\n",
    "def greet(name):\n",
    "    \"\"\"一个简单的问候函数\"\"\"\n",
    "    return f\"Hello, {name}!\"\n",
    "\n",
    "# 调用被装饰的函数\n",
    "print(add(2, 3))\n",
    "print(greet(\"Alice\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b079f292-0b0b-4f64-aec6-6a5ada1d3345",
   "metadata": {},
   "source": [
    "## 面向对象示例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72532145-a4c0-42e6-8c88-7cdd9bd82c4b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 面向对象编程实践示例\n",
    "class BankAccount:\n",
    "    \"\"\"银行账户类，封装账户基本操作\"\"\"\n",
    "    def __init__(self, account_id: str, name: str, balance: float = 0.0):\n",
    "        self._account_id = account_id  # 封装属性（命名约定保护）\n",
    "        self.name = name\n",
    "        self.balance = balance\n",
    "\n",
    "    def deposit(self, amount: float):\n",
    "        \"\"\"存款操作\"\"\"\n",
    "        if amount <= 0:\n",
    "            raise ValueError(\"存款金额必须大于0\")\n",
    "        self.balance += amount\n",
    "        print(f\"成功存入 ¥{amount:.2f}，当前余额：¥{self.balance:.2f}\")\n",
    "\n",
    "    def withdraw(self, amount: float):\n",
    "        \"\"\"取款操作（包含业务逻辑校验）\"\"\"\n",
    "        if amount <= 0:\n",
    "            raise ValueError(\"取款金额必须大于0\")\n",
    "        if self.balance < amount:\n",
    "            raise InsufficientFundsError(\"余额不足\")\n",
    "        self.balance -= amount\n",
    "        print(f\"成功取出 ¥{amount:.2f}，当前余额：¥{self.balance:.2f}\")\n",
    "\n",
    "    def get_balance(self) -> float:\n",
    "        \"\"\"获取当前余额\"\"\"\n",
    "        return self.balance\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"账户 {self._account_id} | 户名 {self.name} | 余额 ¥{self.balance:.2f}\"\n",
    "\n",
    "\n",
    "class InsufficientFundsError(Exception):\n",
    "    \"\"\"自定义异常类（继承异常体系）\"\"\"\n",
    "    pass\n",
    "\n",
    "\n",
    "class BankSystem:\n",
    "    \"\"\"银行系统类（对象管理器）\"\"\"\n",
    "    def __init__(self):\n",
    "        self.accounts = {}\n",
    "\n",
    "    def create_account(self, account_id: str, name: str):\n",
    "        \"\"\"创建新账户\"\"\"\n",
    "        if account_id in self.accounts:\n",
    "            raise ValueError(\"账户ID已存在\")\n",
    "        new_account = BankAccount(account_id, name)\n",
    "        self.accounts[account_id] = new_account\n",
    "        print(f\"成功创建账户：{new_account}\")\n",
    "\n",
    "    def get_account(self, account_id: str) -> BankAccount:\n",
    "        \"\"\"获取指定账户\"\"\"\n",
    "        if account_id not in self.accounts:\n",
    "            raise KeyError(\"账户不存在\")\n",
    "        return self.accounts[account_id]\n",
    "\n",
    "    def batch_deposit(self, account_ids: list, amount: float):\n",
    "        \"\"\"批量存款操作（演示多对象管理）\"\"\"\n",
    "        for acc_id in account_ids:\n",
    "            try:\n",
    "                account = self.get_account(acc_id)\n",
    "                account.deposit(amount)\n",
    "            except Exception as e:\n",
    "                print(f\"账户 {acc_id} 操作失败：{str(e)}\")\n",
    "\n",
    "\n",
    "# 使用示例\n",
    "if __name__ == \"__main__\":\n",
    "    bank = BankSystem()\n",
    "    \n",
    "    # 创建测试账户\n",
    "    bank.create_account(\"1001\", \"张三\")\n",
    "    bank.create_account(\"1002\", \"李四\")\n",
    "\n",
    "    # 单账户操作\n",
    "    try:\n",
    "        acc1 = bank.get_account(\"1001\")\n",
    "        acc1.deposit(1000)\n",
    "        acc1.withdraw(500)\n",
    "    except InsufficientFundsError as e:\n",
    "        print(e)\n",
    "\n",
    "    # 批量操作\n",
    "    bank.batch_deposit([\"1001\", \"1002\"], 200)\n",
    "\n",
    "    # 查看最终状态\n",
    "    print(\"\\n最终账户状态：\")\n",
    "    for acc in bank.accounts.values():\n",
    "        print(acc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e549f043-31f6-44a3-a82d-0952c2009667",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 关于OOP特性验证的综合示例\n",
    "from abc import ABC, abstractmethod\n",
    "import math\n",
    "\n",
    "# --- 抽象与继承 ---\n",
    "class Vehicle(ABC):\n",
    "    \"\"\"\n",
    "    车辆的抽象基类。\n",
    "    这是一个抽象类，不能直接实例化，必须由子类实现其抽象方法。\n",
    "    \"\"\"\n",
    "    def __init__(self, make, model, year):\n",
    "        # 封装约定：私有属性通常以单下划线开头\n",
    "        self._make = make  \n",
    "        self._model = model\n",
    "        self._year = year\n",
    "        # 名称修饰（Name Mangling）：以双下划线开头的属性会被Python改写名称，\n",
    "        # 旨在避免子类意外覆盖父类的私有属性。\n",
    "        # 外部访问时看起来像私有，但仍可以通过 _ClassName__attribute 访问。\n",
    "        self.__running = False \n",
    "\n",
    "    @abstractmethod\n",
    "    def start_engine(self):\n",
    "        \"\"\"\n",
    "        抽象方法：启动引擎。\n",
    "        子类必须实现此方法。\n",
    "        \"\"\"\n",
    "        pass\n",
    "\n",
    "    def stop_engine(self):\n",
    "        \"\"\"停止车辆引擎的方法。\"\"\"\n",
    "        if self.__running:\n",
    "            print(f\"{self.make} {self.model} 的引擎已停止。\")\n",
    "            self.__running = False\n",
    "        else:\n",
    "            print(f\"{self.make} {self.model} 的引擎已关闭。\")\n",
    "\n",
    "    def get_info(self):\n",
    "        \"\"\"获取车辆基本信息的方法。\"\"\"\n",
    "        return f\"{self._year} 年 {self._make} {self._model}\"\n",
    "\n",
    "    # --- 使用 @property 实现封装 ---\n",
    "    @property\n",
    "    def make(self):\n",
    "        \"\"\"制造商属性的getter方法。\"\"\"\n",
    "        return self._make\n",
    "\n",
    "    @property\n",
    "    def model(self):\n",
    "        \"\"\"型号属性的getter方法。\"\"\"\n",
    "        return self._model\n",
    "\n",
    "    @property\n",
    "    def year(self):\n",
    "        \"\"\"年份属性的getter方法。\"\"\"\n",
    "        return self._year\n",
    "\n",
    "    @property\n",
    "    def is_running(self):\n",
    "        \"\"\"引擎是否正在运行的属性的getter方法。\"\"\"\n",
    "        return self.__running\n",
    "\n",
    "    # 特殊方法：用于字符串表示（通过 print() 实现多态）\n",
    "    def __str__(self):\n",
    "        \"\"\"返回车辆对象的字符串表示。\"\"\"\n",
    "        status = \"运行中\" if self.is_running else \"已关闭\"\n",
    "        return f\"车辆：{self.get_info()} (引擎：{status})\"\n",
    "\n",
    "\n",
    "class Car(Vehicle):\n",
    "    \"\"\"一个汽车类，继承自Vehicle。\"\"\"\n",
    "    def __init__(self, make, model, year, num_doors):\n",
    "        # 调用父类的构造函数\n",
    "        super().__init__(make, model, year) \n",
    "        self.num_doors = num_doors\n",
    "\n",
    "    def start_engine(self): # 实现抽象方法\n",
    "        \"\"\"启动汽车引擎的方法。\"\"\"\n",
    "        if not self.is_running:\n",
    "            # 访问被名称修饰的父类私有属性以修改其内部状态\n",
    "            self._Vehicle__running = True\n",
    "            print(f\"汽车 {self.make} {self.model} 的引擎已启动。轰隆隆！\")\n",
    "        else:\n",
    "            print(f\"汽车 {self.make} {self.model} 的引擎已在运行中。\")\n",
    "\n",
    "    # 重写 Vehicle 类的 __str__ 方法，并使用 super() 调用父类方法\n",
    "    def __str__(self):\n",
    "        \"\"\"返回汽车对象的字符串表示。\"\"\"\n",
    "        base_str = super().__str__()\n",
    "        return f\"{base_str}，车门数：{self.num_doors}\"\n",
    "\n",
    "class ElectricCar(Car):\n",
    "    \"\"\"一个电动汽车类，继承自Car。\"\"\"\n",
    "    def __init__(self, make, model, year, num_doors, battery_kwh):\n",
    "        super().__init__(make, model, year, num_doors)\n",
    "        self.battery_kwh = battery_kwh\n",
    "\n",
    "    # 再次重写 start_engine 方法\n",
    "    def start_engine(self):\n",
    "        \"\"\"启动电动汽车系统的方法。\"\"\"\n",
    "        if not self.is_running:\n",
    "            # 同样访问被名称修饰的父类属性以修改其内部状态\n",
    "            self._Vehicle__running = True \n",
    "            print(f\"电动汽车 {self.make} {self.model} 系统已激活。(静音)\")\n",
    "        else:\n",
    "            print(f\"电动汽车 {self.make} {self.model} 已在运行中。\")\n",
    "\n",
    "    # 再次重写 __str__ 方法\n",
    "    def __str__(self):\n",
    "        # 注意：这里的 super().__str__() 调用的是 Car 类的 __str__ 方法\n",
    "        base_str = super().__str__()\n",
    "        return f\"{base_str}，电池容量：{self.battery_kwh} 千瓦时\"\n",
    "\n",
    "# --- 多态性实际应用 ---\n",
    "# 接受任何 Vehicle 子类型（由于继承和需要的鸭子类型）\n",
    "def operate_vehicle(vehicle: Vehicle): \n",
    "    \"\"\"操作车辆的通用函数，展示多态性。\"\"\"\n",
    "    print(f\"\\n正在操作：{vehicle.get_info()}\")\n",
    "    vehicle.start_engine()\n",
    "    vehicle.start_engine() # 再次尝试启动\n",
    "    print(vehicle) # 调用对象的特定 __str__ 方法\n",
    "    vehicle.stop_engine()\n",
    "    print(f\"是否运行中？ {vehicle.is_running}\")\n",
    "\n",
    "\n",
    "# --- 实例化与使用 ---\n",
    "my_car = Car(\"丰田\", \"凯美瑞\", 2024, 4)\n",
    "my_ecar = ElectricCar(\"特斯拉\", \"Model 3\", 2025, 4, 75)\n",
    "\n",
    "# 操作普通汽车\n",
    "operate_vehicle(my_car)\n",
    "# 操作电动汽车\n",
    "operate_vehicle(my_ecar)\n",
    "\n",
    "# 访问属性\n",
    "print(f\"\\n我的汽车品牌：{my_car.make}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
